<?php 
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
use frontend\models\User;
use yii\web\Session;

/**
* @name : 鲁海龙
*/
class LoginController extends Controller
{
	public $layout = 'login_main';
	public function actionLogin()
	{
		$model = new \frontend\models\User();
	    	return $this->render('login', [
	        	'model' => $model,
	    	]);
	    
	}
	//显示注册页面
	public function actionRegister()
	{
	    $model = new \frontend\models\User_details();
	    return $this->render('signup', [
	        'model' => $model,
	    ]);
	}

	//注册用户入库
	public function actionAdd_user()
	{	
		$data = Yii::$app->request->post() ? Yii::$app->request->post() : '';
		if (!empty($data)) {
			if($data['User_details']['pwd'] == $data['User_details']['repwd']){
				$UserModel = New User();
				$res = $UserModel->add_User($data['User_details']);
				if($res['err']){
					$session = new Session();
					$session->open();
					$session['user'] = ['user_id'=>$res['user_id'],'email'=>$data['User_details']['email']];
					return $this->redirect('index.php?w=home/index');
				}else{
					exit("注册失败,请重试");
				}
			}
			else
			{
				return $this->redirect($_SERVER['HTTP_REFERER']);
			}
		}else{
			return $this->redirect('index.php?w=login/login');
		}
	}

	//登录处理
	public function actionLogin_do()
	{
		$model = new \frontend\models\User();
		if (Yii::$app->request->post()) {
			$data = Yii::$app->request->post();
			$res = $model->find()->where(['email'=>$data['email'],'password'=>$data['password']])->One();
	    	if (!empty($res)) {
	    		$session = new Session();
				$session->open();
				$session['user'] = ['user_id'=>$res['id'],'email'=>$res['email']];
				$json['error'] = true;
				$json['msg']   = '登录成功';
	    	}else{
	    		$json['error'] = false;
				$json['msg']   = '登录失败';
	    	}
	        // form inputs are valid, do something here
	        return json_encode($json);
	    }
	}

}
?>